#!/bin/bash
export LANG=C
. /etc/init.d/functions
CONF_DIR=/etc/libvirt/qemu
IMG_DIR=/var/lib/libvirt/images

function create_vm(){
    if  [ -e ${IMG_DIR}/${1}.img ];then
        echo_warning
        echo "vm ${1}.img is exists"
        return 1
    else
        qemu-img create -b ${IMG_DIR}/.BaseOS.qcow2 -f qcow2 ${IMG_DIR}/${1}.img 20G &>/dev/null
        sed -e "s,node_base,${1}," ${IMG_DIR}/.node_base.xml >${CONF_DIR}/${1}.xml
        sudo virsh define ${CONF_DIR}/${1}.xml &>/dev/null
        echo_success
        echo "vm ${1} create"
    fi
}
function remove_vm(){
    read _ img <<<$(sudo virsh domblklist $1 2>/dev/null |grep -P "^[^T-]+")
    if [ -e "${img}" ];then
        sudo virsh destroy  $1 &>/dev/null
        sudo virsh undefine $1 &>/dev/null
        rm -f ${img}
        echo_success
        echo "vm ${1} delete"
    fi
}
function init_openstack(){
    cd ${CONF_DIR}
    for i in openstack nova01 nova02;do 
        remove_vm ${i}
        cp ${IMG_DIR}/.node_base.xml ./${i}.xml
        qemu-img create -b ${IMG_DIR}/.${i}.qcow2 -f qcow2 ${IMG_DIR}/${i}.img &>/dev/null
    done
    patch -p1 -i ${IMG_DIR}/.openstack.patch
    for i in openstack nova01 nova02;do
        sudo virsh define ${CONF_DIR}/${i}.xml &>/dev/null
        echo_success
        sudo virsh start ${i}
    done
}

# main 
case "$1" in
    create|remove)
    CMD=${1}
    while ((${#} > 1));do
        shift
        ${CMD}_vm ${1}
    done
    ;;
    initvm)
    [[ "$2" == "openstack" ]] && init_openstack
    ;;
    *)
    echo "${0##*/} {create|remove|initvm} vm1 vm2 vm3 ... ..."
    ;;
esac

exit $?
